package object;

import utils.SHA1;

import java.io.*;

public class Commit implements Serializable {
    protected String tree; 		// the sha1 value of present committed Tree
    protected String parent; 	// the sha1 value of the parent Commit
    protected String author; 	// the author's name and timestamp
    protected String committer; // the commits info
    protected String message; 	// the Commit memo
    protected String fmt;       // the mode of the object
    protected String content;   // the content of the object
    protected String key;       // the hash value of this object


    public String getFmt(){
        return this.fmt;
    }
    public String getParent(){
        return this.parent;
    }
    public String getContent(){
        return this.content;
    }
    public String getMessage(){
        return this.message;
    }
    public String getKey(){
        return this.key;
    }
    public Commit(){};

    public Commit(Tree tree, String message) throws Exception{
        this.fmt = "commit";
        this.tree = tree.getKey();
        this.parent = getLastCommit() == null ? "" : getLastCommit();
        this.message = message;


        /*Content of this Commit, like this:
         *Tree bd31831c26409eac7a79609592919e9dcd1a76f2
         *parent d62cf8ef977082319d8d8a0cf5150dfa1573c2b7
         *message xxx
         * */
        this.content = "Tree " + this.tree +
                "\nParent " + this.parent  +
                "\nMessage " + this.message;

        this.key = SHA1.getHash(this.content);

        writeObject();

    }
    public void writeObject() {
        try {

            ObjectOutputStream out =
                    new ObjectOutputStream(new FileOutputStream(".jit" + File.separator + "objects" + File.separator + this.key));
            out.writeObject(this);
            out.close();
        }
        catch(Exception ex){
            ex.printStackTrace();
        }

    }

    public static Commit deserialize(String Id) throws Exception{
        try{
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(".jit" + File.separator + "objects" + File.separator + Id));
            return (Commit) in.readObject();
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
    public String getLastCommit() throws Exception{
        HEAD head = HEAD.deserialize();
        return head.getKey();
    }

}
